import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'
import MusicOcrScanner from '../components/MusicOcrScanner.vue'
import Chat from '../views/Chat.vue'
import Community from '../views/Community.vue'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: { 
      requiresAuth: false,
      transition: 'apple-slide' // 苹果风格滑动
    }
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: {
      transition: 'fade' // 淡入淡出
    }
  },
  {
    path: '/register',
    name: 'Register',
    component: Register,
    meta: {
      transition: 'fade' // 淡入淡出
    }
  },
  {
    path: '/scanner',
    name: 'Scanner',
    component: MusicOcrScanner,
    meta: { 
      requiresAuth: true,
      transition: 'product' // 产品页样式
    }
  },
  {
    path: '/chat',
    redirect: '/chat/c',
    meta: { 
      requiresAuth: true
    }
  },
  {
    path: '/chat/c',
    name: 'ChatHome',
    component: Chat,
    meta: { 
      requiresAuth: true,
      transition: 'slide-left' // 向左滑动
    }
  },
  {
    path: '/chat/c/:id',
    name: 'ChatConversation',
    component: Chat,
    props: true,
    meta: { 
      requiresAuth: true,
      transition: 'slide-left' // 向左滑动
    }
  },
  {
    path: '/community',
    name: 'Community',
    component: Community,
    meta: { 
      requiresAuth: true,
      transition: 'slide-right' // 向右滑动
    }
  },
  {
    path: '/profile',
    name: 'Profile',
    component: () => import('../views/Profile.vue'), // 懒加载个人信息页面
    meta: { 
      requiresAuth: true,
      transition: 'scale' // 缩放效果
    }
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    redirect: '/'
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
  scrollBehavior(to, from, savedPosition) {
    // 页面过渡中添加类
    document.documentElement.classList.add('page-transitioning');
    
    if (savedPosition) {
      // 返回前一个位置
      return new Promise((resolve) => {
        setTimeout(() => {
          document.documentElement.classList.remove('page-transitioning');
          resolve(savedPosition);
        }, 600); // 与过渡时间匹配
      });
    } else {
      // 滚动到顶部
      return new Promise((resolve) => {
        setTimeout(() => {
          document.documentElement.classList.remove('page-transitioning');
          resolve({ top: 0, behavior: 'smooth' });
        }, 600); // 与过渡时间匹配
      });
    }
  }
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('user') !== null
  
  if (to.meta.requiresAuth && !isAuthenticated) {
    // 保存原始URL，包括完整的hash和查询参数
    const fullPath = window.location.href;
    console.log('需要登录，保存当前URL:', fullPath);
    
    // 跳转到登录页并传递重定向信息
    next({
      path: '/login',
      query: { redirect: fullPath }
    })
  } else {
    next()
  }
})

export default router 